<template>
  <div class="register">
    <div class="form-wrap">
      <p class="title" slot="title">
        <Icon type="md-log-in"></Icon>
        欢迎注册
      </p>

      <Form ref="userForm" :model="userFormItem" :label-width="80" :rules="rules">
        <FormItem label="用户名" prop="username">
          <Input v-model="userFormItem.username" placeholder="请输入手机" style="max-width: 200px;width: 20vw"/>
        </FormItem>
        <FormItem label="昵称" prop="nickname" >
          <Input v-model="userFormItem.nickname" placeholder="请输入昵称" style="max-width: 200px;width: 20vw"/>
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input type="password" v-model="userFormItem.password" placeholder="密码为8位以上且包含数字及字母"
                 style="max-width: 300px;width: 20vw"/>
        </FormItem>
        <FormItem label="确认密码" prop="repassword">
          <Input type="password" v-model="userFormItem.repassword" placeholder="请再次输入密码"
                 style="max-width: 300px;width: 20vw"/>
        </FormItem>
        <FormItem label="验证码" prop="code">
          <Input v-model="userFormItem.code" style="max-width: 150px;width: 15vw;margin-right: 5px;"/>
          <Button :loading="getCodeLoading" class="get-code" :disabled="count !== seconds" @click="getCode">
            {{count === seconds ? '获取' : count}}
          </Button>
        </FormItem>
      </Form>

      <div class="btn-submit">
        <Button class="btn" @click="handleSubmit" :loading="loading" :size="size" type="primary">注册</Button>
      </div>
      <div style="padding-top: 10px;font-size: 14px;padding-left: 20px;">
        <router-link to="/login">登录</router-link>
      </div>
    </div>
  </div>
</template>
<script>
  import { register} from '@/api/user'
  import { getSmsCode} from '@/api/sms'
  import {checkPassWord,checkPhoneNum} from '@/libs/util';
  export default {
    data () {
      const validateRePass = (rule, value, callback) => {
        let formItem = null;
        formItem = this.userFormItem;
        if (formItem.password !== formItem.repassword) {
          callback('两次密码输入不一致');
        }
        callback();
      };
      return {
        code_type: 'sms',
        seconds: 60,
        size: 'large',
        loading: false,
        getCodeLoading: false,
        count: 60,
        userFormItem: {
          username: '',
          nickname: '',
          password: '',
          repassword: '',
          code: ''
        },
        rules: {
          username: [
            {required: true, message: '用户名不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!checkPhoneNum(value)) {
                  callback('用户名需要为手机号');
                } else {
                  callback();
                }
              }
            }
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (!checkPassWord(value)) {
                  callback('密码为8位以上且包含数字及字母');
                } else {
                  callback();
                }
              }
            }
          ],
          repassword: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {
              validator: validateRePass
            }
          ],
          code: [
            {required: true, message: '请输入验证码', trigger: 'blur'}
          ],
          nickname: [
            {required: true, message: '请输入昵称', trigger: 'blur'}
          ],
        }
      };
    },
    mounted: function () {
      try {
        this.count = parseInt(sessionStorage.getItem('countDown', this.seconds));
        if (this.count !== this.seconds && this.count > 0) {
          this.countDown();
        } else {
          this.count = this.seconds;
        }
      } catch (e) {
        console.log(e);
      }
    },
    methods: {
      handleSubmit () {
        let vm = this;
        let ref = null;
        let formItem = null;
        formItem = vm.userFormItem;

        ref = vm.$refs.userForm;

        ref.validate((valid) => {
          if (valid) {
            this.loading = true;
            let param = {
              type: 'register',
              code: formItem.code,
              username: formItem.username,
              password: formItem.password,
              nickname: formItem.nickname
            };

            register(param).then(response=> {
              vm.loading = false;
              if (response.data.code === 1) {
                vm.$Message.success('注册成功,请登陆后继续操作');
                vm.$router.push({
                  name: 'login'
                });
              } else {
                vm.$Message.error(response.data.msg);
              }
            }).catch(function (error) {
              console.log(error);
            });
          }
        });
      },
      getCode () {
        let vm = this;
        let formItem = null;
        formItem = vm.userFormItem;

        if (!checkPhoneNum(formItem.username)) {
          vm.$Message.error('用户名需要为手机号');
          return;
        }

        vm.getCodeLoading = true;
        getSmsCode( {
          type: 'register',
          phone: formItem.username
        }).then(response=>{
          vm.getCodeLoading = false;
          if (response.data.code === 1) {
            vm.$Message.success('验证码已发送，有效期10分钟');
            vm.countDown();
          }
        },(error) => {
          vm.getCodeLoading = false;
        });
      },
      countDown () {
        let vm = this;
        if (vm.count === 0) {
          vm.count = vm.seconds;
        } else {
          vm.count--;
          setTimeout(function () {
            vm.countDown();
          }, 1000);
        }
        sessionStorage.setItem('countDown', vm.count);
      },
    }
  };
</script>
<style scoped lang="less">
  .register {
    padding-top: 5vh;
    background: #fafafa;
    height: 100%;
    width: 100%;
  }

  .form-wrap {
    margin: 0 auto;
    max-width: 500px;
    width: 40vw;
    padding: 10px;
    background: white;
    border: #d0cdcd 1px solid;
    border-radius: 10px;
  }

  .title {
    font-size: 24px;
    text-align: center;
    padding: 15px;
  }

  .btn-submit {
    text-align: center;
  }

  .btn {
    max-width: 320px;
    width: 15vw;
  }

  .rd-wrap {
    text-align: center;
    padding: 1vw 0;
  }
</style>
